import Vue from 'vue'
const config = {
  services: {
    system: "/system",
    basebiz: "/basebiz",
    oen: "/oen",
    pem: "/pem",
    afs: '/afs'
  },
  baseUrl: 'http://192.168.0.146/services'
}
import { Common } from 'cby.assist'

/** 下载接口地址 */
const DOWNLOAD_API = `${config.services.system || ''}/download`

/**
 * Vue组件文件下载功能
 */
Vue.prototype.$download = ({ name, storage, bucket }) => download(`${DOWNLOAD_API}?name=${name}&storage=${storage}&bucket=${bucket}`)

/**
 * 通用文件下载地址
 */
export const downloadUrl = ({ name, storage, bucket }) => `${config.baseUrl}${DOWNLOAD_API}?name=${name}&storage=${storage}&bucket=${bucket}&token=${localStorage.getItem('token')}`

/**
 * 通用文件下载功能
 */
export const download = (url, params) => {
  if (!url.startsWith('http')) {
    url = config.baseUrl + url
  }
  if (!params) {
    params = {}
  }
  params.token = localStorage.getItem('token')
  url = Common.parseParam(url, params)
  window.open(url)
}

/**
 * 注册Vue窗体拖拽指令，在窗体标签上写上v-drag就可以使用拖拽
 */
Vue.directive('drag', {
  bind: el => {},
  inserted: el => {
    el.onmousedown = e => {
      const disx = e.pageX - el.offsetLeft
      const disy = e.pageY - el.offsetTop
      document.onmousemove = e => {
        el.style.left = e.pageX - disx + 'px'
        el.style.top = e.pageY - disy + 'px'
      }
      document.onmouseup = () => document.onmousemove = document.onmouseup = null
    }
  },
  updated: el => {}
})

/**
 * 根据ID查询名称
 *
 * @param id
 *            查询编号
 * @param list
 *            查询列表
 * @param idField
 *            编号字段名
 * @param nameField
 *            名称字段名
 * @param childrenField
 *            子集字段名
 * @return 名称
 *
 */
Vue.prototype.$findName = (id, list, idField, nameField = 'name', childrenField) => {
  let name = ''
  const item = Common.recursiveQuery(id, list, idField)
  if (item != null && item[nameField]) {
    name = item[nameField]
  }
  return name
}

/**
 * 获取最大高度限制范围
 *
 * @param height
 *            限制高度
 * @return 高度
 *
 */
Vue.prototype.$limitHeight = (height = 0) => {
  const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
  let limit = (windowHeight || 0) - height
  if (limit < 0) {
    limit = 0
  }
  return limit
}

/**
 * 导出Excel
 *
 * @param params 流数据
 * @param fileName 文件名
 * @return 高度
 *
 */
Vue.prototype.$downloadExcel = (params, fileName = '默认') => {
  var blob = new Blob([params], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }) // 导出xlsx格式的报表
  var objectUrl = window.URL.createObjectURL(blob) // 创建下载后的链接
  var a = document.createElement('a')
  document.body.appendChild(a)
  a.style = 'display: none'
  a.href = objectUrl
  a.download = `${fileName}.xlsx` // 下载后文件名
  a.click() // 点击下载
  document.body.removeChild(a)
  window.URL.revokeObjectURL(objectUrl) // 释放掉blob对象
}
